<style lang="scss">
.buy-item {
  border: 1px solid transparent;
  &.active {
    border-color: #16c560;
    .coin {
      color: #16c560;
    }
  }
}
</style>

<template>
  <view class="pa-4 pt-2">
    <view class="ta-c fz-14 mb-5 op-5"> 我的积分：{{ myCoin }} </view>
    <view class="d-flex gap-2 f-wrap">
      <view
        class="flex-1 bg-cell bdrs-8 py-4 ta-c lh-1 buy-item"
        :class="{
          active: it.cash == pickCash,
        }"
        style="min-width: 30%"
        v-for="it in list"
        :key="it.cash"
        @click="pickCash = it.cash"
      >
        <view class="coin">
          <span class="fz-18 fw-b">+{{ it.coin }}</span>
          <span class="fz-12 ml-1">积分</span>
        </view>
        <view class="op-5 mt-3 fz-13">￥{{ it.cash }}元</view>
      </view>
    </view>

    <view class="pa-8"></view>
    <q-btn-wrap>
      <u-button type="primary" :loading="paying" @click="onPay"
        >充值{{ pickCash }}元</u-button
      >
      <view class="mt-3 ta-c">
        <q-btn-tiny @click="$navTo('user/buy-log')">
          <span class="link fz-14">充值记录</span>
        </q-btn-tiny>
      </view>
    </q-btn-wrap>
  </view>
</template>

<script>
import { mapState } from "vuex";

export default {
  computed: {
    ...mapState(["userInfo"]),
    myCoin() {
      return this.userInfo.coin || 0;
    },
    showPay() {
      return !this.$inIos || !!this.from;
    },
  },
  data() {
    return {
      list: [1, 5, 10, 20, 50, 100].map((cash) => {
        return {
          coin: cash * 10,
          cash: cash * 0.1,
        };
      }),
      pickCash: 1,
      paying: false,
      from: null,
    };
  },
  onLoad({ from }) {
    this.from = from;
    this.initUser();
    if (!this.showPay) {
      // this.onPay();
    }
  },
  methods: {
    initUser() {
      if (!this.userInfo.id) {
        this.$store.dispatch("mpLogin");
      } else {
        // this.$store.dispatch("getUserInfo");
      }
    },
    async onPay() {
      try {
        if (!this.showPay) {
          // return this.$alert("由于相关规范，iOS端暂不可充值");
        }
        this.paying = true;
        const { data } = await uni.$api.post("/coin/auth/prepay", {
          cash: this.pickCash,
        });
        this.$loading();
        const info = await uni.$h.wechatPay(data.payment);
        console.log(info);
        const paid = 1; //await this.getPaid(data.order_no);
        this.$toast(paid ? "已支付" : "支付成功", 1);
        await this.$sleep(paid ? 600 : 800);
        await this.$store.dispatch("getUserInfo");
        this.$navBack();
      } catch (error) {
        console.log(error);
        uni.hideLoading();
      }
      this.paying = false;
    },
  },
};
</script>
